package com.ssrs.framework.web.config;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author ssrs
 */
@Configuration
public class ThreadPoolConfig {
    private static final Log log = LogFactory.get(ThreadPoolConfig.class);
    //参数初始化
    public static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

    /**
     * 核心线程池大小
     */
    @Value("${thread.pool.corePoolSize}")
    private int corePoolSize;

    /**
     * 最大可创建的线程数
     */
    @Value("${thread.pool.maxPoolSize}")
    private int maxPoolSize;

    /**
     * 队列最大长度
     */
    @Value("${thread.pool.queueCapacity}")
    private int queueCapacity;

    /**
     * 线程池维护线程所允许的空闲时间
     */
    @Value("${thread.pool.keepAliveSeconds}")
    private int keepAliveSeconds;

    @Bean(name = "simpleThreadPoolTaskExecutor")
    public ThreadPoolTaskExecutor simpleThreadPoolTaskExecutor() {
        return new ThreadPoolTaskExecutor();
    }

    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor(@Qualifier("simpleThreadPoolTaskExecutor") ThreadPoolTaskExecutor executor) {
        executor.initialize();
        if (corePoolSize == 0) {
            corePoolSize = Math.max(2, Math.min(CPU_COUNT - 1, 4));
        }
        executor.setCorePoolSize(corePoolSize);
        if (maxPoolSize == 0) {
            maxPoolSize = CPU_COUNT * 2 + 1;
        }

        //线程名字前缀
        executor.setThreadNamePrefix("TaskExecutor-");

        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程池对拒绝任务(无线程可用)的处理策略
        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        log.info("任务线程池-核心线程数定义为[" + corePoolSize + "], 最大支持的线程数量为[" + maxPoolSize + "], 线程池维护线程所允许的空闲时间[" + keepAliveSeconds + "].");

        // 重点：使用 TTL 提供的 TtlExecutors
        return TtlExecutors.getTtlExecutor(executor);
    }

    /**
     * 执行周期性或定时任务
     */
    @Bean(name = "scheduledExecutorService")
    protected ScheduledExecutorService scheduledExecutorService() {
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(corePoolSize,
                new ThreadFactoryBuilder()
                        .setNamePrefix("schedule-pool-").setDaemon(true).build());
        return TtlExecutors.getTtlScheduledExecutorService(executorService);
    }

    public int getCorePoolSize() {
        return corePoolSize;
    }

    public void setCorePoolSize(int corePoolSize) {
        this.corePoolSize = corePoolSize;
    }

    public int getMaxPoolSize() {
        return maxPoolSize;
    }

    public void setMaxPoolSize(int maxPoolSize) {
        this.maxPoolSize = maxPoolSize;
    }

    public int getQueueCapacity() {
        return queueCapacity;
    }

    public void setQueueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
    }

    public int getKeepAliveSeconds() {
        return keepAliveSeconds;
    }

    public void setKeepAliveSeconds(int keepAliveSeconds) {
        this.keepAliveSeconds = keepAliveSeconds;
    }
}
